﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ImgUpload
{
    public class ImageService
    {
        /// <summary>
        /// Convert Image to Byte[]
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public byte[] ImageToBytes(Image image)
        {
            ImageFormat format = image.RawFormat;
            using (MemoryStream ms = new MemoryStream())
            {
                if (format.Equals(ImageFormat.Jpeg))
                {
                    image.Save(ms, ImageFormat.Jpeg);
                }
                else if (format.Equals(ImageFormat.Png))
                {
                    image.Save(ms, ImageFormat.Png);
                }
                else if (format.Equals(ImageFormat.Bmp))
                {
                    image.Save(ms, ImageFormat.Bmp);
                }
                else if (format.Equals(ImageFormat.Gif))
                {
                    image.Save(ms, ImageFormat.Gif);
                }
                else if (format.Equals(ImageFormat.Icon))
                {
                    image.Save(ms, ImageFormat.Icon);
                }
                byte[] buffer = new byte[ms.Length];
                //Image.Save()会改变MemoryStream的Position，需要重新Seek到Begin
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(buffer, 0, buffer.Length);
                return buffer;
            }
        }
        

        /// <summary>
        /// Convert Byte[] to Image
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public Image BytesToImage(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer);
            Image image = System.Drawing.Image.FromStream(ms);
            return image;
        }
        
        /// <summary>
        /// Convert Byte[] to a picture and Store it in file
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public string SaveImageStream(string fileName, string ImageName, Stream stream,out string suffix)
        {
            string file = fileName + "\\" + ImageName;
            Image image = Image.FromStream(stream);//   BytesToImage(buffer);
            ImageFormat format = image.RawFormat;

            if (format.Equals(ImageFormat.Jpeg))
            {
                suffix = ".jpeg";
            }
            else if (format.Equals(ImageFormat.Png))
            {
                suffix = ".png";
            }
            else if (format.Equals(ImageFormat.Bmp))
            {
                suffix = ".bmp";
            }
            else if (format.Equals(ImageFormat.Gif))
            {
                suffix = ".gif";
            }
            else if (format.Equals(ImageFormat.Icon))
            {
                suffix = ".icon";
            }
            else
                suffix = ".jpeg";
            file += suffix;
            FileInfo info = new FileInfo(file);
            Directory.CreateDirectory(info.Directory.FullName);

            File.WriteAllBytes(file, ImageToBytes(image));
            return file;
        }

        /// <summary>
        /// Convert Byte[] to a picture and Store it in file
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public string GetImageSuffix( Stream stream)
        {
            Image image = Image.FromStream(stream);//   BytesToImage(buffer);
            ImageFormat format = image.RawFormat;
            string suffix = "";
            if (format.Equals(ImageFormat.Jpeg))
            {
                suffix = ".jpeg";
            }
            else if (format.Equals(ImageFormat.Png))
            {
                suffix = ".png";
            }
            else if (format.Equals(ImageFormat.Bmp))
            {
                suffix = ".bmp";
            }
            else if (format.Equals(ImageFormat.Gif))
            {
                suffix = ".gif";
            }
            else if (format.Equals(ImageFormat.Icon))
            {
                suffix = ".icon";
            }
            else
                suffix = ".jpeg";
            return suffix;
        }

        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="originalFileFullName">原图片地址</param>
        /// <param name="afterConversionFileFullName">压缩后保存图片地址</param>
        /// <param name="flag">压缩质量（数字越小压缩率越高）1-100</param>
        /// <param name="size">压缩后图片的最大大小</param>
        /// <param name="isFirst">是否是第一次调用</param>
        /// <returns></returns>
        public Stream CompressImage(Stream oldStream, int flag = 90, int size = 300)
        {
            Image iSource = Image.FromStream(oldStream);
            ImageFormat tFormat = iSource.RawFormat;

            int dHeight = iSource.Height / 2;
            int dWidth = iSource.Width / 2;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);
            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();

            //以下代码为保存图片时，设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;

            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    MemoryStream ms = new MemoryStream();
                    ob.Save(ms, jpegICIinfo, ep);

                    if (ms.Length > 1024 * size)
                    {
                        flag = flag - 10;
                        return CompressImage(oldStream, flag, size);
                    }
                    //需要把其实位置设为0 要不然阿里云无法上传
                    ms.Position = 0;
                    return ms;
                }
                else
                {
                    return oldStream;
                }
            }
            catch (Exception ex)
            {
                return oldStream;
            }
        }
    }
}
